package com.hcy.app.screen.cap

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hcy.app.api.AddSessionForm
import com.hcy.app.api.LoginAccount
import com.hcy.app.data.GlobalState
import com.hcy.app.data.dao.SettingsRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class CapViewModel @Inject constructor(
    private val  capRepository :CapRepository,
    private val settingsRepo: SettingsRepository
): ViewModel() {
    private val _capState = MutableStateFlow(CapStatus(
        config = CapConfig(),
        userInfo = UserInfo(roles = emptyList())
    ))
    val capState = _capState.asStateFlow()


    private inline fun updateState(transform: CapStatus.() -> CapStatus) {
        _capState.update{ state -> state.transform() }
    }

    init {
        loadConfig()
    }
    // 加载初始配置
    fun loadConfig(){
        viewModelScope.launch(Dispatchers.IO) {
            updateState{copy(config =capRepository.getConfig() )}
            settingsRepo.loadCapToken()
            if (GlobalState.CapToken !="" && GlobalState.CapTokenExpires>(System.currentTimeMillis()/1000L)){
                updateState{copy(userInfo = UserInfo(GlobalState.CapUsername, GlobalState.CapRoles,isLoaded = true) )}
            }
        }
    }
    // 保存配置信息
    fun saveConfig(config: CapConfig){
        viewModelScope.launch(Dispatchers.IO) {
            capRepository.saveConfig(config)
            updateState{copy(config = config )}
        }
    }
    // 处理用户登录
    fun capLogin(config: CapConfig,onComplete:(Boolean) -> Unit){
        viewModelScope.launch(Dispatchers.IO) {
            saveConfig(config)
            var res= capRepository.login( LoginAccount(config.username, config.password) )
            if (res.result!=null){
                settingsRepo.saveCapToken(res.result.token,res.result.expires.toLong(),res.result.roles,res.result.username  )
                updateState{copy(userInfo = UserInfo(nickname = res.result.username, roles = res.result.roles,isLoaded = true) )}
                onComplete(true)
            }else{
                onComplete(false)
            }
        }
    }
    // 获取列表信息
    suspend fun getLinks(): List<LinkDto>{
        return capRepository.getLinkList()
    }
    // 创建会话信息
    suspend fun createCapSession(data:AddSessionForm): String{
        return capRepository.createCapSession(data)
    }
}

data class CapStatus(
    val config:CapConfig ,
    val userInfo: UserInfo ,
)

data class CapConfig(
    var username: String = "",
    var password: String = "",
    var serAddr: String = "",
)

data class UserInfo(
    val nickname: String="",
    val roles: List<String>,
    val isLoaded: Boolean =false
)